package com.jeesite.modules.dataview.specialWork.service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.jeesite.common.config.Global;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.ServiceException;
import com.jeesite.common.utils.excel.ExcelImport;
import com.jeesite.common.validator.ValidatorUtils;
import com.jeesite.modules.task.action.entity.DcSupTaskActionDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.dataview.specialWork.entity.DcSupSpecialWork;
import com.jeesite.modules.dataview.specialWork.dao.DcSupSpecialWorkDao;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * 专项工作-事项清单Service
 * @author dbl
 * @version 2022-09-13
 */
@Service
@Transactional(readOnly=false)
public class DcSupSpecialWorkService extends CrudService<DcSupSpecialWorkDao, DcSupSpecialWork> {
	
	/**
	 * 获取单条数据
	 * @param dcSupSpecialWork
	 * @return
	 */
	@Override
	public DcSupSpecialWork get(DcSupSpecialWork dcSupSpecialWork) {
		return super.get(dcSupSpecialWork);
	}
	
	/**
	 * 查询分页数据
	 * @param dcSupSpecialWork 查询条件
	 * @return
	 */
	@Override
	public Page<DcSupSpecialWork> findPage(DcSupSpecialWork dcSupSpecialWork) {
		return super.findPage(dcSupSpecialWork);
	}
	
	/**
	 * 查询列表数据
	 * @param dcSupSpecialWork
	 * @return
	 */
	@Override
	public List<DcSupSpecialWork> findList(DcSupSpecialWork dcSupSpecialWork) {
		return super.findList(dcSupSpecialWork);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param dcSupSpecialWork
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(DcSupSpecialWork dcSupSpecialWork) {
		super.save(dcSupSpecialWork);
	}
	
	/**
	 * 更新状态
	 * @param dcSupSpecialWork
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(DcSupSpecialWork dcSupSpecialWork) {
		super.updateStatus(dcSupSpecialWork);
	}
	
	/**
	 * 删除数据
	 * @param dcSupSpecialWork
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(DcSupSpecialWork dcSupSpecialWork) {
		super.delete(dcSupSpecialWork);
	}

	@Transactional(readOnly=false)
	public String importData(MultipartFile file, Date importTime) {
			if (importTime==null){
				importTime = new Date();
			}
			//先删除导入时间的数据
			String importTimeStr = DateUtils.formatDate(importTime,"yyyy-MM-dd");
			dao.deleteByImportDate(importTimeStr);
			if (file == null){
				throw new ServiceException(text("请选择导入的数据文件！"));
			}
			int successNum = 0; int failureNum = 0;
			StringBuilder successMsg = new StringBuilder();
			StringBuilder failureMsg = new StringBuilder();
			try(ExcelImport ei = new ExcelImport(file, 2, 0)){
				List<DcSupSpecialWork> list = ei.getDataList(DcSupSpecialWork.class);
				for (DcSupSpecialWork importData : list) {
					try{
						// 验证数据文件
						importData.setImportTime(importTime);
						String orgCode = dao.getOfficeCodeByOfficeName(importData.getLeaderOrgName());
						if (StringUtils.isBlank(orgCode)) {
							failureNum++;
							failureMsg.append("<br/> 导入失败：第"+failureNum+"行责任单位名称有误");
							continue;
						}else{
							importData.setLeaderOrgCode(orgCode);
						}

						ValidatorUtils.validateWithException(importData);
						this.save(importData);
						successNum++;
						successMsg.append("<br/>" + successNum + "、序号 " + importData.getTaskNum() + " 导入成功");
					} catch (Exception e) {
						failureNum++;
						String msg = "<br/>" + failureNum + "、序号 " + importData.getTaskNum() + " 导入失败：";
						if (e instanceof ConstraintViolationException){
							ConstraintViolationException cve = (ConstraintViolationException)e;
							for (ConstraintViolation<?> violation : cve.getConstraintViolations()) {
								msg += Global.getText(violation.getMessage()) + " ("+violation.getPropertyPath()+")";
							}
						}else{
							msg += e.getMessage();
						}
						failureMsg.append(msg);
						logger.error(msg, e);
					}
				}
			} catch (Exception e) {
				failureMsg.append(e.getMessage());
				logger.error(e.getMessage(), e);
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
				throw new ServiceException(failureMsg.toString());
			}else{
				successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
			}
			return successMsg.toString();

	}

    public Integer queryAllNums(String remarks3,String userCode) {
		return dao.queryAllNums(remarks3,userCode);
    }

	public Integer queryConditionNums(DcSupTaskActionDto dcSupTaskActionDto) {
		String createTaskDate = dcSupTaskActionDto.getCreateTaskDate();
		if(StringUtils.isNotBlank(createTaskDate)){
			String[] date = createTaskDate.split(" ~ ");
			String startDate = date[0];
			String endDate = date[1];
			dcSupTaskActionDto.setStartTime(startDate);
			dcSupTaskActionDto.setEndTime(endDate);
		}else{
			Calendar cal = Calendar.getInstance();
			String  startTime  =cal.get(Calendar.YEAR) +"-01-01";
			String endTime  = (cal.get(Calendar.YEAR)  + 1)+"-01-01";
			dcSupTaskActionDto.setStartTime(startTime);
			dcSupTaskActionDto.setEndTime(endTime);
		}
		return dao.queryConditionNums(dcSupTaskActionDto);
	}
}